import { doLogin, doLogout } from "@/api/auth";
import { LoginResult, Token } from "@/api/auth/type";
import { router } from "@/router";
import { defineStore } from "pinia";
import { computed, ref } from "vue";
import { useUserStore } from "./user";
import { User } from "@/api/user/type";

export const useAuthStore = defineStore('auth', () => {
    const isLogin = ref(false)
    const token = ref({} as Token)
    const getToken = computed(() => `${token.value.prefix} ${token.value.content}`)
    const getIsLogin = computed(() => isLogin.value)
    
    function login(username: string, password: string, redirectPath?: string) {
        doLogin({
            username, password, rememberMe: false,
            captcha: {
                captchaBase64: '',
                captchaKey: '',
                captchaCode: ''
            }
        }).then(async (res) => {
            const data = res.data as LoginResult;
            token.value = data.token;
            isLogin.value = true;
            await saveStatus();
            init();
            // 使用提供的重定向路径，如果没有则默认为首页
            router.push(redirectPath || "/home");
        })
    }
    
    function logout() {
        doLogout().then(async () => {
            isLogin.value = false;
            token.value = {} as Token;
            const userStore = useUserStore();
            userStore.user = {} as User;
            
            await clearStoredToken();
            
            goLogin();
        }).catch(error => {
            console.error('登出失败', error);
            isLogin.value = false;
            token.value = {} as Token;
            goLogin();
        });
    }
    
    async function clearStoredToken() {
        try {
            localStorage.removeItem("auth_token");
        } catch (error) {
            console.error('清除存储的令牌失败', error);
        }
    }
    
    async function init() {
        try {
            const tokenStr = localStorage.getItem("auth_token");
            if (tokenStr) {
                const parsedToken = JSON.parse(tokenStr) as Token;
                if (parsedToken && typeof parsedToken === 'object') {
                    token.value = parsedToken;
                    isLogin.value = true;
                } else {
                    goLogin();
                }
            } else {
                goLogin();
            }
            
            if (isLogin.value) {
                const userStore = useUserStore();
                await userStore.doGetUserInfo();
            }
        } catch (error) {
            console.error('初始化认证状态失败', error);
            goLogin();
        }
    }
    
    async function saveStatus() {
        try {
            localStorage.setItem("auth_token", JSON.stringify(token.value));
        } catch (error) {
            console.error('保存认证状态失败', error);
        }
    }
    
    function goLogin() {
        router.push("/login");
    }
    
    return {
        token,
        getToken, getIsLogin,
        login, logout, init, goLogin
    }
})